home *** CD-ROM | disk | FTP | other *** search
- Path: snews.tcel.com!netway
- From: tech@netway.ab.ca (Ritchie Annand)
- Newsgroups: comp.lang.c++
- Subject: Re: Multiple Inheritance Pointer Problem
- Date: 8 Apr 1996 10:43:39 GMT
- Organization: Telnet Canada (403) 262-5859 info@tcel.com
- Message-ID: <4kaqkr$pp3@challenge.tcel.com>
- References: <31622A26.3633@nmaa.org>
- NNTP-Posting-Host: 204.209.150.53
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- >#include <iostream.h>
- >
- >class foo
- >{
- >public:
- > void PrintMe(void) { cerr << "this = " << this << endl; }
- >};
- >
- >class bar
- >{
- >#ifdef OFF_BY_4
- >public:
- > int b;
- >#endif
- >};
- >
- >class foobar : public foo, public bar
- >{
- >#ifdef OFF_BY_4
- >public:
- > int fb;
- >#endif
- >};
- >
- >class barfoo : public bar, public foo
- >{
- >#ifdef OFF_BY_4
- >public:
- > int bf;
- >#endif
- >};
- >
- >main()
- >{
- > foobar fb;
- > barfoo bf;
- >
- > cerr << "&fb = " << &fb << endl;
- > fb.PrintMe();
- > cerr << "&bf = " << &bf << endl;
- > bf.PrintMe();
- >
- > return(0);
- >}
-
- The problem you're having is that there are some compromises that had to be
- made in the use of pointers with multiple inheritance.
-
- PrintMe is a member of the foo class, therefore all objects that call it must
- be from a descendant class of foo. To be a proper descendant, the class must
- have all of foo's data members in the same order at the same relative
- position as foo.
-
- With the foobar class, you have no problems, because the foo part of the
- class comes at the front, just like it would in regular single inheritance.
-
- With the barfoo class, in order for barfoo to satisfy the requirements of
- having the data members in the same spot as foo, the this pointer is OFFSET
- when given to foo. The foo part of the class starts AFTER the bar part of
- the class does. This occurs even if foo has no data members (as in your
- example)
-
- The 2 and 4 offsets you're describing come from the way different compilers
- will handle the ints - some will align the int to a longword (4 bytes), and
- some will keep it as a word (2 byte). Try putting more data items into bar,
- and you'll see the pointer get more and more offset.
-
- There are some things you can do to work around this, but the dirt-simplest
- way is to make sure the object that needs to check its own address it the
- first one in the inheritance list.
-
- --=- Ritchie A.
-